<template>
  <div id="file-editor" v-show="openShow">
    <div id="file-header">
      <div id="item"><i class="fas fa-file-alt"></i>&nbsp;&nbsp;{{filePath}}</div>
      <div id="item" @click="openShow=false"><i class="h-icon-close"></i></div>
    </div>
    <div id="file-content">
      <editor v-model="codeText" @init="editorInit" :lang="lang" :theme="theme" :height="height" :width="width"></editor>
      <Loading text="正在保存，请勿中途退出" :loading="saveLoading"></Loading>
    </div>
    <div id="file-button">
      <div><Button :disabled="undoButtonDisabled" @click="editor.undo()" style="display:inline-block;" color="primary"><i style="font-size:16px;" class="fas fa-undo"></i>&nbsp;&nbsp;
          撤销（CTRL+Z）</Button>
        <Button :disabled="redoButtonDisabled" @click="editor.redo()" style="display:inline-block;" color="primary"><i style="font-size:16px;" class="fas fa-redo"></i>&nbsp;&nbsp;
          恢复（CTRL+Y）</Button>
      </div>

      <div style="text-align:right;flex:1"><Button :disabled="saveButtonDisabled" @click="saveFile" style="display:inline-block;" color="primary"><i style="font-size:16px;"
            class="fas fa-save"></i>&nbsp;&nbsp;保
          存</Button></div>
    </div>
  </div>
</template>

<script>
import Rcon from '@/libs/rcon'
export default {
  props: {
    // value: {
    //   type: String
    // },
    lang: {
      type: String,
      default: 'sh'
    },
    theme: {
      type: String,
      default: 'chrome'
    },
    height: {
      type: String
    },
    width: {
      type: String
    },
  },
  data() {
    return {
      saveLoading: false,
      saveButtonDisabled: true,
      undoButtonDisabled: true,
      redoButtonDisabled: true,
      filePath: '',
      openShow: false,
      codeText: '',
      editor: null,
      selectServerData: null,
    }
  },
  watch: {
    // value(val) {
    //   this.filePath = val
    // },
    // codeText(val) {
    //   this.$emit('input', val)
    // }
  },
  mounted: function () {
    // if (this.value) {
    //   this.readfile(this.value)
    // }
  },
  components: {
    editor: require('vue2-ace-editor'),
  },
  methods: {
    async saveFile() {
      this.saveLoading = true
      let ret = await this.$file.upfile(this.filePath, new Blob([this.codeText]))
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.saveLoading = false
        return
      }
      this.editor.session.getUndoManager().markClean();
      this.updateToolbar(this.editor)
      this.$emit('saveFileChange', ret.files)
      let fileName = this.filePath.substring(this.filePath.lastIndexOf("/") + 1, this.filePath.length);
      let extensionName = this.filePath.substring(this.filePath.lastIndexOf(".") + 1, this.filePath.length);
      fileName = fileName.replace('.' + extensionName, '')
      // console.log(extensionName,fileName,(this.filePath.indexOf('/oxide/config/')!=-1 || this.filePath.indexOf('/oxide/lang/')!=-1))
      if (extensionName == 'json' && (this.filePath.indexOf('/oxide/config/') != -1 || this.filePath.indexOf('/oxide/lang/') != -1)) {
        console.log(this.selectServerData)
        try {
          let rcon = new Rcon(this.selectServerData.rcon.port, this.selectServerData.rcon.password)
          rcon.reloadPlugin(fileName)
        } catch (error) {

        }
      }
      console.log(this.selectServerData, '保存', this.filePath)
      this.saveLoading = false
    },
    openFile(path, serverData) {
      return new Promise(async (resolve, reject) => {
        this.filePath = path
        this.selectServerData = serverData
        let ret = await this.$file.verifyfile(path)
        if (ret.code == -1) {
          this.openShow = false
          resolve(this.openShow)
          this.$Notice({
            type: 'error',
            title: '错误',
            content: ret.msg
          });
          return
        }
        let extensionName = path.substring(path.lastIndexOf(".") + 1, path.length);
        switch (extensionName) {
          case 'txt':
            this.editor.getSession().setMode(`ace/mode/sh`)
            break;
          case 'json':
            this.editor.getSession().setMode(`ace/mode/json`)
            break;
          case 'log':
            this.editor.getSession().setMode(`ace/mode/sh`)
            break;
          case 'xml':
            this.editor.getSession().setMode(`ace/mode/xml`)
            break;
          case 'cfg':
            this.editor.getSession().setMode(`ace/mode/sh`)
            break;
          case 'js':
            this.editor.getSession().setMode(`ace/mode/javascript`)
            break;
          default:
            this.editor.getSession().setMode(`ace/mode/sh`)
            break;
        }
        // console.log(extensionName)
        ret = await this.$file.readfile(path)
        if (ret.indexOf(`"code":-1`)!=-1) {
          this.openShow = false
          resolve(this.openShow)
          this.$Notice({
            type: 'error',
            title: '错误',
            content: '不存在此配置文件'
          });
          return
        }
        this.editor.session.setValue(ret)
        this.openShow = true
        resolve(this.openShow)
      })

    },
    updateToolbar(editor) {
      this.saveButtonDisabled = editor.session.getUndoManager().isClean();
      this.undoButtonDisabled = !editor.session.getUndoManager().hasUndo();
      this.redoButtonDisabled = !editor.session.getUndoManager().hasRedo();
    },
    editorInit(editor) {
      //   console.log(editor)
      this.editor = editor
      this.editor.on("input", () => { this.updateToolbar(editor) });
      require('brace/ext/language_tools') //language extension prerequsite...
      require('brace/mode/html')
      require('brace/mode/javascript')    //language
      require('brace/mode/less')
      require('brace/mode/json')
      require('brace/mode/sh')
      require('brace/mode/text')
      require('brace/mode/xml')
      require('brace/theme/chrome')
      this.$emit('codeEditorInit', this)
      //   require('brace/snippets/javascript') //snippet
    }
  }
}
</script>
<style lang="less" scoped>
#file-editor {
  height: calc(100% - 22px);
  z-index: 1000;
  width: calc(100% - 22px);
  //   background: red;
  background: #fff;
  position: absolute;
  display: flex;
  flex-direction: column;
  //   align-items: center;
  #file-header {
    //   flex: 1;
    // height: 50px;
    padding: 8px;
    // line-height: 50px;
    display: flex;
    #item {
      color: rgb(45, 173, 143);
      padding: 8px 15px;
      margin: 0 2px;
      border-radius: 4px;
      background: rgba(47, 218, 178, 0.3);
      &:first-child {
        flex: 1;
        font-weight: bold;
      }
      &:last-child {
        cursor: pointer;
        align-self: flex-end;
      }
    }
    // #file-close {
    //   cursor: pointer;
    //   i {
    //     color: rgb(45, 173, 143);
    //     background: rgba(47, 218, 178, 0.3);
    //     padding: 10px;
    //     border-radius: 100px;
    //   }
    // }
  }
  #file-content {
    border: solid 1px rgba(0, 0, 0, 0.1);
    // padding: 10px;
    margin: 0 10px;
    padding-top: 0;
    // flex: 1;
    height: calc(100% - 110px);
  }
  #file-button {
    padding: 10px;
    //   background: red;
    display: flex;
    align-items: center;
  }
}
</style>